from flask import Flask, render_template, jsonify
import os
import paramiko
import threading
import time
import json
from datetime import datetime

app = Flask(__name__)

# 全局变量存储相机数据和完成率
camera_data = {}
completion_rates = {}

def load_camera_ids():
    """从文件读取相机ID"""
    with open('/home/gwac/dwl/cut_web/cut_web/camreaid', 'r') as f:
        return [line.strip() for line in f.readlines()]

def fetch_camera_data(camera_id):
    """从单台相机服务器获取JSON数据"""
    try:
        # 补零到3位作为相机名称
        camera_name = f"{int(camera_id):03d}"
        ip = f"172.28.2.{camera_id}"
        
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username='gwac', password='gwac1234')
        
        # 获取JSON文件
        sftp = ssh.open_sftp()
        remote_path = f"/home/gwac/dwl/{camera_name}_{datetime.now().strftime('%y%m%d')}.json"
        local_path = f"/home/gwac/dwl/cut_web/data/{camera_name}_{datetime.now().strftime('%y%m%d')}.json"
        
        sftp.get(remote_path, local_path)
        sftp.close()
        ssh.close()
        
        # 处理JSON数据
        with open(local_path) as f:
            data = json.load(f)
        
        # 分析每张fit图的完成状态
        steps = ["A_cat", "A_img_orig", "B_align_template_cat", "C_align", 
                "D_combine", "E_diff_align", "F_diff", "G_diff_cat", 
                "H_wcs_template", "I_resi_object_win", "J_resi_object_classify"]
        
        image_stats = []
        total_images = 0
        total_completed_steps = 0
        
        # 分析每张fit图的完成情况
        for image_name, image_data in data.items():
            if image_name.endswith('.fit'):
                total_images += 1
                completed_steps = [step for step, status in image_data['steps'].items() if status == 'yes']
                incomplete_steps = [step for step, status in image_data['steps'].items() if status == 'none']
                total_completed_steps += len(completed_steps)
                
                image_stats.append({
                    "image_name": image_name,
                    "completed_steps": completed_steps,
                    "incomplete_steps": incomplete_steps,
                    "completion_rate": (len(completed_steps) / len(steps)) * 100
                })
        
        # 计算整体完成率
        overall_completion = (total_completed_steps / (total_images * len(steps))) * 100 if total_images > 0 else 0
        
        # 打印详细的图像处理状态
        print(f"\nCamera {camera_name} - Detailed image processing status:")
        print(f"Total images processed: {total_images}")
        print(f"Overall completion rate: {overall_completion:.1f}%")
        
        for stat in image_stats[:5]:  # 只打印前5张图的详细状态
            print(f"\nImage: {stat['image_name']}")
            if stat['incomplete_steps']:
                print(f"  - Incomplete steps: {', '.join(stat['incomplete_steps'])}")
            else:
                print("  - All steps completed")
            print(f"  - Completion rate: {stat['completion_rate']:.1f}%")
        
        return {
            "camera_id": camera_id,
            "camera_name": camera_name,
            "data_path": local_path,
            "image_stats": image_stats,
            "overall_completion": overall_completion,
            "total_images": total_images,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
    except Exception as e:
        print(f"Error fetching data for camera {camera_id}: {e}")
        return None

def update_all_camera_data():
    """更新所有相机数据"""
    global camera_data, completion_rates
    camera_ids = load_camera_ids()
    all_camera_data = {}
    
    for camera_id in camera_ids:
        data = fetch_camera_data(camera_id)
        if data:
            all_camera_data[data["camera_name"]] = data
            completion_rates[data["camera_name"]] = data["overall_completion"]
    
    camera_data = all_camera_data
    # 10分钟后再次执行
    threading.Timer(600, update_all_camera_data).start()

@app.route('/')
def index():
    """主页面显示相机完成状态"""
    return render_template('index.html', 
                         camera_data=camera_data,
                         completion_rates=completion_rates)

@app.route('/api/data')
def get_camera_data():
    """提供API接口获取相机数据"""
    return jsonify({
        "camera_data": camera_data,  # 现在包含所有相机的详细数据
        "completion_rates": completion_rates,
        "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    })

if __name__ == '__main__':
    # 确保数据目录存在
    os.makedirs('/home/gwac/dwl/cut_web/data', exist_ok=True)
    
    # 启动定时任务
    update_all_camera_data()
    app.run(host='0.0.0.0', port=5010)
